﻿using NotificationService.DAL;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace NotificationService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class NotificationService : INotification
    {
        PhoneDAL phoneDal;
        public NotificationService()
        {
            phoneDal = new PhoneDAL();
        }

        public bool Register(string deviceId, string url)
        {
            return phoneDal.InsertPhone(deviceId, url);
        }

        public void SendToast(string url, string title, int count)
        {
            string content = count == 1 ? "There is a new ringtone" : count > 1 ? "There are " + count + " new ringtones" : "";  
            if (string.IsNullOrEmpty(content))
            {
                return;
            }
            string message = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                   "<wp:Toast>" +
                        "<wp:Text1>" + title + "</wp:Text1>" +
                        "<wp:Text2>" + content + "</wp:Text2>" +
                        "<wp:Param>/MainPage.xaml?count=" + count + "</wp:Param>" +
                   "</wp:Toast> " +
                "</wp:Notification>";
            byte[] msgBytes = new UTF8Encoding().GetBytes(message);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "text/xml";
            request.ContentLength = msgBytes.Length;
            request.Headers["X-MessageID"] = Guid.NewGuid().ToString();
            request.Headers["X-WindowsPhone-Target"] = "toast";
            request.Headers["X-NotificationClass"] = "2";

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(msgBytes, 0, msgBytes.Length);
            }
        }

        public void SendToAllClient(string title, int count)
        {
            using (SqlDataReader reader = phoneDal.GetAllUrl())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string url = reader["Url"].ToString();
                        SendToast(url, title, count);
                    }
                }
            }
        }
    }
}
